import 'package:framework/data/model/domain_bean.dart';
import 'package:module_discover/pages/model/filter_model.dart';
import 'package:module_discover/utils/dis_cons.dart';

class FilterConverter {
  static List<BaseFilterItem> convertDomainBeans(List<DomainBean> beans) {
    return beans.map(_convertDomainBean).toList();
  }

  static BaseFilterItem _convertDomainBean(DomainBean bean) {
    return ValueFilterItem(
      key: bean.key ?? 'root_${bean.id}',
      title: bean.title ?? '未命名分类',
      type: "",
      children: bean.children?.map(_convertFilterChild).toList() ?? [],
      rawValue: null,
    );
  }

  static BaseFilterItem _convertFilterChild(DomainFilterChild child) {
    switch (child.type) {
      case DisCons.multiChoice:
      case DisCons.singleChoice:
        return _buildSingleChoice(child);
      case DisCons.input:
        return _buildInputItem(child);
      case DisCons.rangeSelector:
        return _buildRangeItem(child);
      default:
        return _buildFallbackItem(child);
    }
  }

  static BaseFilterItem _buildSingleChoice(DomainFilterChild child) {
    return ValueFilterItem(
      key: child.key ?? "",
      title: child.name ?? "",
      type: child.type ?? "s_choice",
      children: _convertAllOptions(child),
      rawValue: _getRawValue(child),
      custom: _convertFilterCustom(child.custom),
    );
  }

  /// 综合处理options/data/optional等字段
  static List<BaseFilterItem> _convertAllOptions(DomainFilterChild child) {
    final List<BaseFilterItem> items = [];

    // 优先处理options
    if (child.options?.isNotEmpty ?? false) {
      items.addAll(child.options!.map(_convertFilterOption));
    }
    // 次优先处理optional
    else if (child.optional?.isNotEmpty ?? false) {
      items.addAll(child.optional!.map(_convertFilterOption));
    }
    // 最后处理data
    else if (child.data?.isNotEmpty ?? false) {
      items.addAll(child.data!.map(_convertDynamicItem));
    }

    return items;
  }

  /// custom
  static BaseFilterItem? _convertFilterCustom(Map<String, dynamic>? custom) {
    if (custom == null) {
      return null;
    }
    return ValueFilterItem(
      key: custom['key']?.toString() ?? '',
      title: custom['name']?.toString() ?? '',
      type: custom['type']?.toString() ?? '',
      children: custom['data'] ?? [],
      value: custom['value']?.toString() ?? '',
      rawValue: '',
    );
  }

  /// 转换option项
  static BaseFilterItem _convertFilterOption(DomainFilterOption option) {
    return ValueFilterItem(
      key: option.name ?? "",
      title: option.name ?? "",
      type: option.type ?? "",
      children: _buildDomainFilterChildItem(option.children),
      rawValue: option.value,
      value: option.value ?? "",
    );
  }

  /// 处理动态数据项
  static BaseFilterItem _convertDynamicItem(dynamic item) {
    // 类型1: Map结构数据
    if (item is Map<String, dynamic>) {
      String name = "";
      String value = "";

      if (_isStandardNameValue(item)) {
        name = item['name']?.toString().trim() ?? "";
        value = item['value']?.toString().trim() ?? "";
      }
      // 类型2处理：单键值结构
      else if (_isSingleKeyValue(item)) {
        final entry = item.entries.first;
        name = entry.key;
        value = entry.value?.toString().trim() ?? "";
      }
      return InputFilterItem(
        key: name,
        title: name,
        value: value,
        type: item['type']?.toString() ?? '',
        hintText: item['value']?.toString(),
      );
    }

    // 类型2: 字符串直接转换
    if (item is String) {
      return ValueFilterItem(
        key: 'str_${item.hashCode}',
        title: item,
        type: 'text',
        rawValue: item,
      );
    }

    // 类型3: 其他类型兜底处理
    return ValueFilterItem(
      key: 'unknown_${item.hashCode}',
      title: '未知类型数据',
      type: 'unknown',
      rawValue: item,
    );
  }

  /// 提取原始值
  static dynamic _getRawValue(DomainFilterChild child) {
    return {
      'origin_pid': child.pid,
      'custom_data': child.custom,
      's_data': child.sData,
    };
  }

  static BaseFilterItem _buildInputItem(DomainFilterChild child) {
    final List<BaseFilterItem> items = [];
    if (child.optional?.isNotEmpty ?? false) {
      items.addAll(child.optional!.map(_convertFilterOption));
    }
    return InputFilterItem(
      key: child.key ?? "",
      title: child.name ?? "",
      hintText: child.hint,
      type: child.type ?? "",
      children: items,
    );
  }

  static List<BaseFilterItem> _buildDomainFilterChildItem(
      List<DomainFilterChild>? children) {
    List<BaseFilterItem> list = [];
    children?.forEach((data) {
      list.add(ValueFilterItem(
        key: data.key ?? "",
        title: data.name ?? "",
        type: data.type ?? "",
        children: _convertAllOptions(data),
        rawValue: null,
      ));
    });

    return list;
  }

  static BaseFilterItem _buildRangeItem(DomainFilterChild child) {
    return RangeFilterItem(
      key: child.key ?? "",
      title: child.name ?? "",
      type: child.type ?? "",
      defaultMin: (child.sData?['from'] as num?)?.toDouble() ?? 0,
      defaultMax: (child.sData?['to'] as num?)?.toDouble() ?? 100,
    );
  }

  static BaseFilterItem _buildFallbackItem(DomainFilterChild child) {
    return ValueFilterItem(
      key: child.key ?? "",
      title: child.name ?? '未知类型',
      type: 'unknown',
      rawValue: null,
    );
  }

  /// 判断是否为标准name/value结构
  static bool _isStandardNameValue(Map<String, dynamic> map) {
    return map.containsKey('name') && map.containsKey('value');
  }

  /// 判断是否为单键值结构
  static bool _isSingleKeyValue(Map<String, dynamic> map) {
    return map.keys.length == 1;
  }
}
